package com.zybzzz.workapp.fragment;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.zybzzz.workapp.MainActivity;
import com.zybzzz.workapp.R;
import com.zybzzz.workapp.entry.PlanDate;
import com.zybzzz.workapp.entry.PlanMsg;
import com.zybzzz.workapp.entry.PlanMsgLab;
import com.zybzzz.workapp.entry.SinglePlanDateLab;

import java.util.Calendar;
import java.util.UUID;

public class TaskItemFragment extends Fragment {

    private PlanMsg planMsg;
    private PlanDate planDate;
    private Integer taskIndexNum;
    private CheckBox finishedCheckBox;
    private EditText taskEditText;
    private Button dateBn;
    private Button timeBn;
    private TextView dateshow;
    private TextView timeshow;

    private static final String TASK_ARG_PLAN_ID="plan_id";
    private static final String TASK_ARG_PLAN_INDEX="task_index";
    private static final String TASK_ARG_EXIST_PLAN="exist_plan";


    /**
     * 创建TaskItemFragment的静态方法
     * 由PlanmsgFragment调用
     * 在PlanmsgFragment中传递 id（表示PlanMSg，暂时没用到），计划对象，当前详细计划的index（代表第几条详细计划）
     * @param: [planid, existPlanMsg, index]
     * @return: com.zybzzz.workapp.fragment.TaskItemFragment
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    public static TaskItemFragment makeNewInstance(UUID planid,PlanMsg existPlanMsg,Integer index){
        Bundle args=new Bundle();
        args.putSerializable(TASK_ARG_PLAN_ID,planid);
        args.putSerializable(TASK_ARG_PLAN_INDEX,index);
        args.putSerializable(TASK_ARG_EXIST_PLAN,existPlanMsg);

        TaskItemFragment fragment=new TaskItemFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        //无论如何都会包含ARG_PLAN_ID 不做有效性判断
        UUID planid=(UUID) getArguments().getSerializable(TASK_ARG_PLAN_ID);
        //仅对id在容器中是否存在进行判断
//        if (PlanMsgLab.get(getActivity()).getPlanMsgById(planid)==null){
//            //找不到新创建
//            planMsg=new PlanMsg();
//            planMsg.setId(planid);
//        }else {
//            //找的到直接取出来
//            planMsg=PlanMsgLab.get(getActivity()).getPlanMsgById(planid);
//        }
        //上面被注解掉的代码没有用，因为直接把PlanMsg对象传过来了，不用再通过id去取
        planMsg=(PlanMsg)getArguments().getSerializable(TASK_ARG_EXIST_PLAN);
        taskIndexNum=(Integer)getArguments().getSerializable(TASK_ARG_PLAN_INDEX);
        planDate=new PlanDate();
    }


    /**
     * 生命周期方法
     * @param: [inflater, container, savedInstanceState]
     * @return: android.view.View
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //加载原先设计好的界面
        View v=inflater.inflate(R.layout.fragment_task_list,container,false);
        finishedCheckBox=(CheckBox)v.findViewById(R.id.taskCheckBox);
        taskEditText=(EditText)v.findViewById(R.id.taskEditText);
        dateBn=(Button)v.findViewById(R.id.button);
        timeBn=(Button)v.findViewById(R.id.button2);
        dateshow=(TextView)v.findViewById(R.id.textView3);
        timeshow=(TextView)v.findViewById(R.id.textView7);
        //对checkbox进行一系列判断 然后设置值
        if (/*planMsg.getTaskFinisheds().size()>taskIndexNum&&*/planMsg.getTaskFinisheds().get(taskIndexNum)!=null){
            finishedCheckBox.setChecked(planMsg.getTaskFinisheds().get(taskIndexNum));
        }else {
            finishedCheckBox.setChecked(false);
        }

        //可能一直是true
        finishedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            /**
             * 为checkbox添加监听，在checkbox状态改变的时候，将相应的状态设置到PlanMsg中
             * @param: [buttonView, isChecked]
             * @return: void
             * @author: ZhangYiBo
             * @date: 2020/10/15
             */
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (planMsg.getTaskFinisheds().size()>taskIndexNum&&planMsg.getTaskFinisheds().get(taskIndexNum)!=null){
//                    planMsg.getTaskFinisheds().set(taskIndexNum,isChecked);
//                }else {
//                    planMsg.getTaskFinisheds().add(isChecked);
//                }
                //直接更改状态
                planMsg.getTaskFinisheds().set(taskIndexNum,isChecked);
                planDate.setTaskStatus(isChecked);
            }
        });

        //对文本框进行一系列判断
        //如果原先对详细计划有过设置，就加载设置
        if (/*planMsg.getTaskItems().size()>taskIndexNum&&*/planMsg.getTaskItems().get(taskIndexNum)!=null){
            taskEditText.setText(planMsg.getTaskItems().get(taskIndexNum));
        }
        taskEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }


            /**
             * 当文本框中的文本改变的时候同步更新到PlanMsg中
             * @param: [s, start, before, count]
             * @return: void
             * @author: ZhangYiBo
             * @date: 2020/10/15
             */
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (planMsg.getTaskItems().size()>taskIndexNum&&planMsg.getTaskItems().get(taskIndexNum)!=null){
//                    planMsg.getTaskItems().set(taskIndexNum,s.toString());
//                }else {
//                    planMsg.getTaskItems().add(s.toString());
//                }

                //直接更改即可
                planMsg.getTaskItems().set(taskIndexNum,s.toString());
                planDate.setTaskText(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //在这里设置原来已经有的Date和Time
        if (planMsg.getTaskDates().get(taskIndexNum)!=null){
            dateshow.setText(planMsg.getTaskDates().get(taskIndexNum));
        }else {
            dateshow.setText("暂未设置日期");
        }
        if (planMsg.getTaskTimes().get(taskIndexNum)!=null){
            timeshow.setText(planMsg.getTaskTimes().get(taskIndexNum));
        }else {
            timeshow.setText("暂未设置时间");
        }


        dateBn.setOnClickListener(new View.OnClickListener()        //
        {
            @Override
            public void onClick(View source)
            {
                Calendar c = Calendar.getInstance();
                // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
                new DatePickerDialog(TaskItemFragment.super.getContext(),
                        // 绑定监听器
                        new DatePickerDialog.OnDateSetListener()
                        {
                            @Override
                            public void onDateSet(DatePicker dp, int year,
                                                  int month, int dayOfMonth)
                            {
                                dateshow.setText(year + "-" + ((month + 1)>=10?(month + 1):("0"+(month + 1))) + "-" + (dayOfMonth>=10?dayOfMonth:("0"+dayOfMonth)));
                                planDate.setFinishDate(year + "-" + ((month + 1)>=10?(month + 1):("0"+(month + 1))) + "-" + (dayOfMonth>=10?dayOfMonth:("0"+dayOfMonth)));
                                planMsg.getTaskDates().set(taskIndexNum,year + "-" + ((month + 1)>=10?(month + 1):("0"+(month + 1))) + "-" + (dayOfMonth>=10?dayOfMonth:("0"+dayOfMonth)));

                            }
                        }
                        //设置初始日期
                        , c.get(Calendar.YEAR)
                        , c.get(Calendar.MONTH)
                        , c.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        timeBn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View source)
            {
                Calendar c = Calendar.getInstance();
                // 创建一个TimePickerDialog实例，并把它显示出来。
                new TimePickerDialog(TaskItemFragment.super.getContext(), AlertDialog.THEME_HOLO_LIGHT,
                        // 绑定监听器
                        new TimePickerDialog.OnTimeSetListener()
                        {
                            @Override
                            public void onTimeSet(TimePicker tp, int hourOfDay,
                                                  int minute)
                            {
                                timeshow.setText( (hourOfDay>=10?hourOfDay:("0"+hourOfDay)) + ":" + (minute>=10? minute :("0"+minute)));
                                planDate.setTaskTime((hourOfDay>=10?hourOfDay:("0"+hourOfDay)) + ":" + (minute>=10? minute :("0"+minute)));
                                planMsg.getTaskTimes().set(taskIndexNum,(hourOfDay>=10?hourOfDay:("0"+hourOfDay)) + ":" + (minute>=10? minute :("0"+minute)));
                            }
                        }
                        //设置初始时间
                        , c.get(Calendar.HOUR_OF_DAY)
                        , c.get(Calendar.MINUTE)
                        //true表示采用24小时制
                        , true).show();
            }
        });


        SinglePlanDateLab dateLab=SinglePlanDateLab.get();
        SinglePlanDateLab.get().addPlanDate(planDate);


        return v;
    }
}
